import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { AccountService } from '@services/account.service';
import { UserService } from '@services/user.service';
import { WindowService } from '@services/window.service';
import { AuthKey } from '@configs/constant';
import { first } from 'rxjs/operators';

export interface LoginArg {
  name: string;
  password: string;
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styles: [],
  providers: [AccountService, UserService],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoginComponent implements OnInit {
  formValues: LoginArg = {
    name: '',
    password: ''
  };
  constructor(
    private router: Router,
    private accountServe: AccountService,
    private userServe: UserService,
    private windowServe: WindowService
  ) { }

  ngOnInit() {
  }
  onSubmit(form: NgForm) {
    if (form.valid) {
      this.accountServe.login(form.value).pipe(first()).subscribe(({ user, token }) => {
        window.localStorage.setItem(AuthKey, token);
        this.userServe.setUser(user);
        this.windowServe.alert('登录成功');
        this.router.navigateByUrl('/home/heroes').then();
      });
    }
  }
}
